package tgc.tdu.tgq.demo.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import tgc.tdu.tgq.demo.entity.SysUser;
import tgc.tdu.tgq.demo.repository.SysUserRepository;

@Component
public class UserUtils {
	//数据库访问类
	@Autowired
	private SysUserRepository userDAO;
	
	//获取当前的用户
	public SysUser getUser() {
		//获取Security上下文，userDADetails凭证对象
		UserDetails userDADetails=(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		String username=userDADetails.getUsername();
		return userDAO.findByUsername(username);
	}
	//判断用户拥有那个角色
	public boolean hasRole(String roleCode) {
		//getAuthorities获取角色凭证信息
		Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
		List<String> roleCodes=new ArrayList<>();
		//遍历用户凭证
		for (GrantedAuthority authority : authorities) {
			//将所有角色编码封装在roleCodes
			roleCodes.add(authority.getAuthority());
		}
		return roleCodes.contains(roleCode); 
	}
}
